#include "abc-article-manager-synchronizer.h"

#include "util/logger/logger.h"
#include "util/fs.h"

#include "abc-article-manager.h"
#include "abc-article-manager-controller.h"


static const char *name() {
    return "AbcArticleManagerSynchronizer ";
}

AbcArticleManagerSynchronizer::AbcArticleManagerSynchronizer(AbcArticleManagerController &controller, Executor &executor)
    : controller_(controller)
    , controllerThread_(executor) {
    
    LOGD << name() << "constructed";
    
    managerThread_.post([this] {
        manager_ = new AbcArticleManager;
        manager_->setOnGenerateSucceedCallback([this](std::shared_ptr<book::Book> book) {
            controllerThread_.post([this, book]() {
                controller_.notifyDataGenerated(book);
            });
        });
        manager_->forceGenerate();
    });
}

AbcArticleManagerSynchronizer::~AbcArticleManagerSynchronizer() {
    LOGD << name() << "destructed";

    managerThread_.post([this] {
        delete manager_;
        manager_ = nullptr;
    });
}

void AbcArticleManagerSynchronizer::notifyRepoPushed() {
    LOGD << name() << "notify repo pushed";

    managerThread_.post([this] {
        if (manager_) {
            manager_->forceGenerate();
        }
    });
}

void AbcArticleManagerSynchronizer::afterBookDataDirActivated(const fs::path &dir) {
    LOGD << name() << "after book data dir activated: " << dir;

    managerThread_.post([this, dir] {
        if (manager_) {
            manager_->afterBookDataDirActivated(dir);
        }
    });
}

